package com.share.exception;

import com.share.domain.vo.RestResponse;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import java.util.Locale;

/**
 * author:caifan
 * date:2020/1/2
 */
@RestControllerAdvice
public class SysExceptionHandler {

    @Resource
    private MessageSource messageSource;

    @ExceptionHandler(value = SysException.class)
    public ResponseEntity<RestResponse> handlerSysException(Locale locale, SysException sysException) {
        return new ResponseEntity<>(new RestResponse(sysException.getCode(), getErrMsg(sysException.getMessage(), locale), "Sys"), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(value = ApiException.class)
    public ResponseEntity<RestResponse> handlerApiException(Locale locale, SysException sysException) {
        return new ResponseEntity<>(new RestResponse(sysException.getCode(), getErrMsg(sysException.getMessage(), locale), "API"), HttpStatus.BAD_REQUEST);
    }

    private String getErrMsg(String message, Locale locale) {
        String errorMsg = "default error";
        try {
            errorMsg = messageSource.getMessage(message, null, locale);
        } catch (Exception e) {

        }
        return errorMsg;
    }
}
